The loop macro essentially
creates a mini-language within Lisp that is specially tailored
for describing loops. While this language is a little
strange-looking by the standards of regular Lisp, it turns out to
be very easy to learn and well-suited to its purpose.
Since loop is a macro, all parsing of the loop
language takes place at byte-compile time; compiled
loops are just as efficient as the equivalent
while loops written longhand.
A loop construct consists of a series of clauses, each introduced by a symbol like
forordo. Clauses are simply strung together in the argument list ofloop, with minimal extra parentheses. The various types of clauses specify initializations, such as the binding of temporary variables, actions to be taken in the loop, stepping actions, and final cleanup.Common Lisp specifies a certain general order of clauses in a loop:
(loop name-clause var-clauses... action-clauses...)The name-clause optionally gives a name to the implicit block that surrounds the loop. By default, the implicit block is named
nil. The var-clauses specify what variables should be bound during the loop, and how they should be modified or iterated throughout the course of the loop. The action-clauses are things to be done during the loop, such as computing, collecting, and returning values.The Emacs version of the
loopmacro is less restrictive about the order of clauses, but things will behave most predictably if you put the variable-binding clauseswith,for, andrepeatbefore the action clauses. As in Common Lisp,initiallyandfinallyclauses can go anywhere.Loops generally return
nilby default, but you can cause them to return a value by using an accumulation clause likecollect, an end-test clause likealways, or an explicitreturnclause to jump out of the implicit block. (Because the loop body is enclosed in an implicit block, you can also use regular Lispreturnorreturn-fromto break out of the loop.)
The following sections give some examples of the Loop Macro in
action, and describe the particular loop clauses in great detail.
Consult the second edition of Steele's Common Lisp, the
Language, for additional discussion and examples of the
loop macro.